// DOM 元素引用
const navbar = document.querySelector('.navbar');
const navLinks = document.querySelectorAll('.nav-links a');
const skillBars = document.querySelectorAll('.skill-progress');
const contactForm = document.getElementById('contactForm');
const themeToggle = document.getElementById('theme-toggle');

// 当前语言设置
let currentLang = 'zh-CN';

// 深色/浅色模式切换功能
// 初始化主题
function initializeTheme() {
    // 检查是否有保存的主题偏好
    const savedTheme = localStorage.getItem('preferredTheme');
    
    if (savedTheme) {
        // 使用保存的主题
        document.body.classList.toggle('dark-mode', savedTheme === 'dark');
    } else {
        // 检查系统偏好
        const prefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches;
        document.body.classList.toggle('dark-mode', prefersDark);
    }
}

// 切换主题
function toggleTheme() {
    const isDarkMode = document.body.classList.toggle('dark-mode');
    
    // 保存主题偏好到本地存储
    localStorage.setItem('preferredTheme', isDarkMode ? 'dark' : 'light');
    
    // 更新主题切换按钮的图标
    updateThemeIcon(isDarkMode);
}

// 更新主题图标
function updateThemeIcon(isDarkMode) {
    const themeIcon = themeToggle.querySelector('svg');
    
    if (isDarkMode) {
        // 替换为太阳图标
        themeIcon.innerHTML = '<circle cx="12" cy="12" r="5"></circle><line x1="12" y1="1" x2="12" y2="3"></line><line x1="12" y1="21" x2="12" y2="23"></line><line x1="4.22" y1="4.22" x2="5.64" y2="5.64"></line><line x1="18.36" y1="18.36" x2="19.78" y2="19.78"></line><line x1="1" y1="12" x2="3" y2="12"></line><line x1="21" y1="12" x2="23" y2="12"></line><line x1="4.22" y1="19.78" x2="5.64" y2="18.36"></line><line x1="18.36" y1="5.64" x2="19.78" y2="4.22"></line>';
    } else {
        // 替换为月亮图标
        themeIcon.innerHTML = '<path d="M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z"></path>';
    }
}

// 为主题切换按钮添加事件监听器
if (themeToggle) {
    themeToggle.addEventListener('click', toggleTheme);
}

// 初始化主题
initializeTheme();

// 平滑滚动效果
function smoothScroll(target) {
    const element = document.querySelector(target);
    if (element) {
        window.scrollTo({
            top: element.offsetTop - 80, // 减去导航栏高度
            behavior: 'smooth'
        });
    }
}

// 为导航链接添加点击事件监听
navLinks.forEach(link => {
    link.addEventListener('click', function(e) {
        e.preventDefault();
        const target = this.getAttribute('href');
        smoothScroll(target);
    });
});

// 监听滚动事件，改变导航栏样式
window.addEventListener('scroll', function() {
    if (window.scrollY > 50) {
        navbar.style.backgroundColor = 'rgba(51, 51, 51, 0.9)';
        navbar.style.padding = '0.5rem 0';
        navbar.style.boxShadow = '0 2px 10px rgba(0, 0, 0, 0.1)';
    } else {
        navbar.style.backgroundColor = '#333';
        navbar.style.padding = '1rem 0';
        navbar.style.boxShadow = 'none';
    }
    
    // 触发技能条动画
    triggerSkillAnimation();
});

// 技能条动画
function triggerSkillAnimation() {
    const skillsSection = document.querySelector('.skills');
    const sectionTop = skillsSection.offsetTop;
    const sectionBottom = sectionTop + skillsSection.offsetHeight;
    const windowHeight = window.innerHeight;
    const windowBottom = window.scrollY + windowHeight;
    
    if (windowBottom > sectionTop && window.scrollY < sectionBottom) {
        skillBars.forEach(bar => {
            const width = bar.style.width;
            bar.style.width = '0';
            setTimeout(() => {
                bar.style.width = width;
            }, 100);
        });
    }
}

// 表单提交处理
if (contactForm) {
    contactForm.addEventListener('submit', function(e) {
        e.preventDefault();
        
        const formData = new FormData(this);
        const formValues = Object.fromEntries(formData.entries());
        
        // 在实际项目中，这里会发送表单数据到服务器
        // 这里我们只是模拟提交成功
        console.log('表单数据:', formValues);
        
        // 显示提交成功消息（根据当前语言）
        const currentLang = document.documentElement.lang || 'zh-CN';
        if (currentLang === 'en') {
            alert('Thank you for your message! I will get back to you soon.');
        } else {
            alert('感谢您的留言！我会尽快回复您。');
        }
        
        // 重置表单
        this.reset();
    });
}

// 为项目卡片添加悬停效果
const projectItems = document.querySelectorAll('.project-item');
projectItems.forEach(item => {
    item.addEventListener('mouseenter', function() {
        this.style.transform = 'translateY(-5px)';
        this.style.boxShadow = '0 10px 20px rgba(0, 0, 0, 0.1)';
    });
    
    item.addEventListener('mouseleave', function() {
        this.style.transform = 'translateY(0)';
        this.style.boxShadow = '0 0 10px rgba(0, 0, 0, 0.1)';
    });
});

// 创建一个简单的淡入动画函数
function fadeIn(element, duration = 1000) {
    element.style.opacity = '0';
    element.style.transition = `opacity ${duration}ms ease`;
    
    setTimeout(() => {
        element.style.opacity = '1';
    }, 100);
}

// 页面加载完成后执行
window.addEventListener('DOMContentLoaded', function() {
    // 为各个部分添加淡入效果
    const sections = document.querySelectorAll('section');
    sections.forEach(section => {
        fadeIn(section, 1500);
    });
    
    // 初始化技能条宽度为0
    skillBars.forEach(bar => {
        bar.style.width = '0';
    });
    
    // 如果在移动设备上，添加简单的触摸事件支持
    if (window.innerWidth < 768) {
        // 这里可以添加移动设备特定的交互逻辑
    }
});

// 简单的图片懒加载功能
function lazyLoadImages() {
    const images = document.querySelectorAll('img');
    
    images.forEach(img => {
        if (isInViewport(img) && !img.complete) {
            img.src = img.src;
        }
    });
}

// 检查元素是否在视口中
function isInViewport(element) {
    const rect = element.getBoundingClientRect();
    return (
        rect.top <= (window.innerHeight || document.documentElement.clientHeight) &&
        rect.left <= (window.innerWidth || document.documentElement.clientWidth)
    );
}

// 监听滚动事件，实现图片懒加载
window.addEventListener('scroll', lazyLoadImages);

// 初始加载时检查图片
lazyLoadImages();

// 添加返回顶部按钮功能
function createBackToTopButton() {
    const backToTopButton = document.createElement('button');
    backToTopButton.textContent = '↑';
    backToTopButton.id = 'backToTop';
    backToTopButton.style.position = 'fixed';
    backToTopButton.style.bottom = '20px';
    backToTopButton.style.right = '20px';
    backToTopButton.style.padding = '10px 15px';
    backToTopButton.style.backgroundColor = '#4CAF50';
    backToTopButton.style.color = 'white';
    backToTopButton.style.border = 'none';
    backToTopButton.style.borderRadius = '50%';
    backToTopButton.style.cursor = 'pointer';
    backToTopButton.style.opacity = '0';
    backToTopButton.style.transition = 'opacity 0.3s ease';
    backToTopButton.style.zIndex = '999';
    backToTopButton.style.fontSize = '18px';
    backToTopButton.style.width = '40px';
    backToTopButton.style.height = '40px';
    backToTopButton.style.display = 'flex';
    backToTopButton.style.justifyContent = 'center';
    backToTopButton.style.alignItems = 'center';
    
    document.body.appendChild(backToTopButton);
    
    // 点击返回顶部
    backToTopButton.addEventListener('click', function() {
        window.scrollTo({
            top: 0,
            behavior: 'smooth'
        });
    });
    
    // 监听滚动事件，显示/隐藏返回顶部按钮
    window.addEventListener('scroll', function() {
        if (window.scrollY > 300) {
            backToTopButton.style.opacity = '1';
        } else {
            backToTopButton.style.opacity = '0';
        }
    });
}

// 创建返回顶部按钮
createBackToTopButton();

// 多语言支持功能
// 初始化翻译
window.initializeTranslations = function() {
    // 检查是否有保存的语言偏好
    const savedLang = localStorage.getItem('preferredLanguage');
    if (savedLang && window.languages[savedLang]) {
        currentLang = savedLang;
    }
    
    // 应用翻译
    applyTranslations(currentLang);
    
    // 设置语言按钮样式
    updateLanguageButtons();
    
    // 为语言按钮添加点击事件
    setupLanguageButtons();
};

// 应用翻译
function applyTranslations(lang) {
    if (!window.languages || !window.languages[lang]) {
        console.error('Language data not found for:', lang);
        return;
    }
    
    const elements = document.querySelectorAll('[data-i18n]');
    elements.forEach(element => {
        const key = element.getAttribute('data-i18n');
        const translation = window.languages[lang][key];
        
        if (translation) {
            element.textContent = translation;
        }
    });
    
    // 更新HTML的lang属性
    document.documentElement.lang = lang;
}

// 更新语言按钮样式
function updateLanguageButtons() {
    const langZhBtn = document.getElementById('lang-zh');
    const langEnBtn = document.getElementById('lang-en');
    
    if (langZhBtn && langEnBtn) {
        if (currentLang === 'zh-CN') {
            langZhBtn.classList.add('active');
            langEnBtn.classList.remove('active');
        } else {
            langZhBtn.classList.remove('active');
            langEnBtn.classList.add('active');
        }
    }
}

// 设置语言按钮点击事件
function setupLanguageButtons() {
    const langZhBtn = document.getElementById('lang-zh');
    const langEnBtn = document.getElementById('lang-en');
    
    if (langZhBtn) {
        langZhBtn.addEventListener('click', function() {
            changeLanguage('zh-CN');
        });
    }
    
    if (langEnBtn) {
        langEnBtn.addEventListener('click', function() {
            changeLanguage('en');
        });
    }
}

// 切换语言
function changeLanguage(lang) {
    if (lang !== currentLang && window.languages && window.languages[lang]) {
        currentLang = lang;
        applyTranslations(currentLang);
        updateLanguageButtons();
        
        // 保存语言偏好到本地存储
        localStorage.setItem('preferredLanguage', currentLang);
    }
}